package com.yfp.operation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yfp.common.core.domain.R;
import com.yfp.common.datascope.annotation.DataScope;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.operation.domain.MarCoupon;
import com.yfp.operation.domain.StoredValueActivity;
import com.yfp.operation.domain.StoredValueActivityDetail;
import com.yfp.operation.domain.dto.StoredValueActivityDTO;
import com.yfp.operation.mapper.MarCouponMapper;
import com.yfp.operation.mapper.StoredValueActivityDetailMapper;
import com.yfp.operation.service.StoredValueActivityService;
import com.yfp.operation.mapper.StoredValueActivityMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;


/**
* @author admin
* @description 针对表【stored_value_activity(储值活动)】的数据库操作Service实现
* @createDate 2024-11-22 10:17:26
*/
@Service
@Slf4j
public class StoredValueActivityServiceImpl extends ServiceImpl<StoredValueActivityMapper, StoredValueActivity>
    implements StoredValueActivityService{

    @Resource
    private StoredValueActivityMapper storedValueActivityMapper;
    @Resource
    private StoredValueActivityDetailMapper storedValueActivityDetailMapper;
    @Resource
    private MarCouponMapper marCouponMapper;



    /**
     * 储值活动列表
     * @param storedValueActivityDTO
     * @return
     */
    @Override
    @DataScope(deptAlias = "sva")
    public List<StoredValueActivity> activityList(StoredValueActivityDTO storedValueActivityDTO) {
        List<StoredValueActivity> list = storedValueActivityMapper.activityList(storedValueActivityDTO);
        return list;
    }


    /**
     * 新增储值活动
     * @param storedValueActivity
     */
    @Override
    @Transactional
    public R<?> add(StoredValueActivity storedValueActivity) {

        // 校验是否存在相同的活动名称
        Integer count = storedValueActivityMapper.verifyName(storedValueActivity.getName());
        if (count > 0) {
            return R.fail("活动名称重复");
        }

        HashMap<Long, Long> couponCountMap = new HashMap<>();

        // 计算赠送储值金比率
        for (StoredValueActivityDetail svad : storedValueActivity.getSvadList()) {
            if (svad.getType() == 2) {
                BigDecimal bigDecimal = NumberUtil.div(svad.getGiftGold(), svad.getMoney()).setScale(6, RoundingMode.UP);
                svad.setGiftRatio(bigDecimal);
            }

            if (svad.getMarCouponId() != null && svad.getMarCouponCount() != null) {

                if (couponCountMap.containsKey(svad.getMarCouponId())) {
                    Long couponNum = couponCountMap.get(svad.getMarCouponId());
                    couponCountMap.put(svad.getMarCouponId(),couponNum + svad.getMarCouponCount());
                } else {
                    couponCountMap.put(svad.getMarCouponId(), svad.getMarCouponCount());
                }
            }
        }

        if (!CollUtil.isEmpty(couponCountMap)) {
            for (Long couponId : couponCountMap.keySet()) {
                MarCoupon marCoupon = marCouponMapper.selectById(couponId);
                if (BeanUtil.isEmpty(marCoupon) || marCoupon.getSurplusCount() < couponCountMap.get(couponId) || !marCoupon.getStatus().equals(1)) {
                    return R.fail("新增失败，优惠券失效或数量不足");
                }
                if (marCoupon.getReceiveCount() < couponCountMap.get(couponId)) {
                    return R.fail("新增失败，发放数量大于优惠券配置个人可领取数");
                }
            }
        }

        // 将活动失效
        storedValueActivityMapper.updateStatus(null,2);

        Long userId = SecurityUtils.getUserId();
        Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
//        Long userId = 69L;
//        Long deptId = 1L;

        storedValueActivity.setCreateUserId(userId);
        storedValueActivity.setUpdateUserId(userId);
        storedValueActivity.setDeptId(deptId);
        // 新增储值活动
        storedValueActivityMapper.add(storedValueActivity);

        // 新增储值活动详情
        storedValueActivityDetailMapper.add(storedValueActivity);
        return R.ok();
    }


    /**
     * 储值活动详情
     * @param activityId
     * @return
     */
    @Override
    public StoredValueActivity particulars(Long activityId) {

        // 获取活动数据
        StoredValueActivity storedValueActivity = storedValueActivityMapper.selectById(activityId);

        if (BeanUtil.isEmpty(storedValueActivity)) {
            return new StoredValueActivity();
        }

        // 活动详情数据
        List<StoredValueActivityDetail> svadList = storedValueActivityDetailMapper.getByActivityId(activityId);
        if (!CollUtil.isEmpty(svadList)) {
            storedValueActivity.setSvadList(svadList);
        }

        return storedValueActivity;
    }

    /**
     * 根据id修改状态
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(Long id, Integer status) {
        storedValueActivityMapper.updateStatus(id,status);
    }

    /**
     * 储值活动到期失效
     */
    @Override
    public void storedActivityExpire() {
        storedValueActivityMapper.expire();
    }


}




